package Server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import comunicationFrames.Message;

public class MessageWorker implements Runnable {
		private Socket connection;
		private List<Socket> messageConnections;
		private Map<Long, ClientHandler> loggedUsers;

		public MessageWorker(List<Socket> messageConnections,
							 Map<Long, ClientHandler> loggedUsers) {
			super();
			this.messageConnections = messageConnections;
			this.loggedUsers = loggedUsers;
		}

		@Override
		public void run() {
			while (true) {
				synchronized (messageConnections) {
					while (messageConnections.isEmpty()) {
						try {
							messageConnections.wait();
						} catch (InterruptedException e) {
							return;
						}
					}
					connection = (Socket) messageConnections.remove(0);
				}
				handleConnection();
			}
		}
		
		private void handleConnection() {
			try {
				ObjectInputStream socketReader =
						new ObjectInputStream(connection.getInputStream());
				Object o = socketReader.readObject();
				if (o instanceof Message) {
					Message m = (Message) o;
					long number = m.getTo();
					ClientHandler ch = loggedUsers.get(number);
					if (ch != null) {
						ch.sendMessage(m);
					}
				}
				socketReader.close();
			} catch (FileNotFoundException e) {
				System.err.println(
						"Could not find requested file on the server.");
			} catch (IOException e) {
				System.err.println("Error handling a client: " + e);
			} catch (ClassNotFoundException e) {
				System.err.println("Error reading from socket: " + e);
			}
		}
		
	}